<template>
  <teleport to="body">
    <div class="modal" v-if="visible">
      <div class="modal-content">
        <span class="close" @click="closeModal">&times;</span>
        <h2>{{ isRegister? '注册' : '登录' }}</h2>
        <input
          v-model="username"
          type="text"
          placeholder="用户名"
          class="input-field"
        />
        <input
          v-model="password"
          type="password"
          placeholder="密码"
          class="input-field"
        />
        <button
          @click="handleAction"
          class="action-button"
        >
          {{ isRegister? '注册' : '登录' }}
        </button>
        <button
          @click="toggleMode"
          class="action-button secondary"
        >
          {{ isRegister? '切换到登录' : '切换到注册' }}
        </button>
      </div>
    </div>
  </teleport>
</template>

<script setup>
import { ref, defineProps, defineEmits } from 'vue'

const props = defineProps({
  visible: { type: Boolean, default: false },
  isRegister: { type: Boolean, default: true }
})

const emit = defineEmits(['register', 'login', 'toggle', 'close'])

const username = ref('')
const password = ref('')

const closeModal = () => {
  emit('close')
}

const handleAction = () => {
  if (props.isRegister) {
    emit('register', username.value, password.value)
  } else {
    emit('login', username.value, password.value)
  }
  username.value = ''
  password.value = ''
}

const toggleMode = () => {
  emit('toggle')
}
</script>

<style scoped>
.modal {
  display: block;
  position: fixed;
  z-index: 1000;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgba(0, 0, 0, 0.4);
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  background-color: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
  width: 350px;
  position: relative;
}

.close {
  color: #aaa;
  position: absolute;
  right: 20px;
  top: 10px;
  font-size: 30px;
  font-weight: bold;
  transition: color 0.3s ease;
  cursor: pointer;
}

.close:hover,
.close:focus {
  color: black;
  text-decoration: none;
}

.input-field {
  width: 100%;
  padding: 12px 15px;
  margin-bottom: 20px;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 15px;
}

.action-button {
  background-color: #007bff;
  color: white;
  padding: 12px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s ease;
  width: 100%;
  font-size: 16px;
  margin-bottom: 10px;
}

.action-button.secondary {
  background-color: #eaeaea;
  color: #333;
  border: 1px solid #ccc;
}

.action-button:hover {
  background-color: #0056b3;
}
</style>